package com.ktgj.customer.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.exception.LoginException;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.vo.ItineraryVo;
import com.ktgj.customer.mapper.CardMapper;
import com.ktgj.customer.mapper.CustomerCardMapper;
import com.ktgj.customer.mapper.PointRecordMapper;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.*;
import com.ktgj.hotel.api.RemoteHotelService;
import com.ktgj.service.api.RemoteService;
import com.ktgj.service.api.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.mapper.ItineraryMapper;
import com.ktgj.customer.service.IItineraryService;

/**
 * 行程定制Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-09-01
 */
@Service
public class ItineraryServiceImpl implements IItineraryService 
{
    @Autowired
    private ItineraryMapper itineraryMapper;

    @Autowired
    private ILoginService iLoginService;

    @Autowired
    private RemoteService remoteService;

    @Autowired
    private RemoteFlightService remoteFlightService;

    @Autowired
    private PointRecordMapper pointRecordMapper;

    @Autowired
    private RemoteHotelService remoteHotelService;

    @Autowired
    private CustomerCardMapper customerCardMapper;

    @Autowired
    private CardMapper cardMapper;

    /**
     * 查询行程定制
     * 
     * @param itinerary 行程定制ID
     * @return 行程定制
     */
    @Override
    public Itinerary selectItineraryById(Long itinerary)
    {
        return itineraryMapper.selectItineraryById(itinerary);
    }

    /**
     * 查询行程定制列表
     * 
     * @param itinerary 行程定制
     * @return 行程定制
     */
    @Override
    public List<Itinerary> selectItineraryList(Itinerary itinerary)
    {
        return itineraryMapper.selectItineraryList(itinerary);
    }

    /**
     * 新增行程定制
     * 
     * @param itinerary 行程定制
     * @return 结果
     */
    @Override
    public int insertItinerary(Itinerary itinerary)
    {
        itinerary.setCreateTime(DateUtils.getNowDate());
        return itineraryMapper.insertItinerary(itinerary);
    }

    /**
     * 修改行程定制
     * 
     * @param itinerary 行程定制
     * @return 结果
     */
    @Override
    public int updateItinerary(Itinerary itinerary)
    {
        itinerary.setUpdateTime(DateUtils.getNowDate());
        return itineraryMapper.updateItinerary(itinerary);
    }

    /**
     * 批量删除行程定制
     * 
     * @param itinerarys 需要删除的行程定制ID
     * @return 结果
     */
    @Override
    public int deleteItineraryByIds(Long[] itinerarys)
    {
        return itineraryMapper.deleteItineraryByIds(itinerarys);
    }

    /**
     * 删除行程定制信息
     * 
     * @param itinerary 行程定制ID
     * @return 结果
     */
    @Override
    public int deleteItineraryById(Long itinerary)
    {
        return itineraryMapper.deleteItineraryById(itinerary);
    }

    @Override
    public List<Itinerary> selectItineraryItineraryOrder(Long itinerary) {
        //todo 行程多对多
        /*List<Itinerary> lstIt =  itineraryMapper.selectItineraryItineraryOrder(itinerary);
        for (Itinerary it: lstIt) {
            it.getItineraryMiddles();
        }*/
        return itineraryMapper.selectItineraryItineraryOrder(itinerary);
    }

    /**
     * 评价中心
     * */
    @Override
    public List<ItineraryVo> selectItineraryByCustomerId(Long customerId, String evaluation) {
        List<Itinerary> itineraryList = itineraryMapper.selectItineraryByCustomerId(customerId, evaluation);
        List<ItineraryVo> itineraryVoList = new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        SimpleDateFormat mapperFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (Itinerary itinerary : itineraryList) {
            ItineraryVo itineraryVo = new ItineraryVo();
            itineraryVo.setItineraryCustomizeId(itinerary.getItineraryCustomizeId());
            itineraryVo.setDeparturePoint(itinerary.getDeparturePoint());
            itineraryVo.setDestination(itinerary.getDestination());


            String departureTime = format.format(itinerary.getDepartureTime());
            String destinationTime = format.format(itinerary.getDestinationTime());
            departureTime = departureTime.substring(0,2)+"月"+departureTime.substring(3,5)+"日";
            destinationTime = destinationTime.substring(0,2)+"月"+destinationTime.substring(3,5)+"日";

            String departureDate = mapperFormat.format(itinerary.getDepartureTime());
            String destinationDate = mapperFormat.format(itinerary.getDestinationTime());
            long timeStart = 0l;
            long timeEnd = 0l;
            try {
                timeStart=mapperFormat.parse(departureDate).getTime();
                timeEnd =mapperFormat.parse(destinationDate).getTime();
            }catch (Exception e){
                return null;
            }

            long dayCount= (timeEnd-timeStart)/(24*3600*1000);
            long dayNum = timeEnd-timeStart;
            if (dayCount == 0 && dayNum > 0){
                dayCount = 1;
            }

            itineraryVo.setJourneyTime("行程时间:"+departureTime+"-"+destinationTime+" (共"+dayCount+"天)");
            itineraryVo.setItineraryAppraise(itinerary.getItineraryAppraise());
            itineraryVo.setItineraryAppraiseContent(itinerary.getItineraryAppraiseContent());
            itineraryVo.setDropOff(itinerary.getDropOff());
            itineraryVo.setVipRoom(itinerary.getVipRoom());
            itineraryVo.setFlight(itinerary.getFlight());
            itineraryVo.setPickUp(itinerary.getPickUp());
            itineraryVo.setAnonymous(itinerary.getAnonymous());
            itineraryVoList.add(itineraryVo);
        }
        return itineraryVoList;
    }

    /**
     * 评价行程
     * */
    @Override
    public int updateItineraryByItinerary(ItineraryVo itineraryVo, Long customerId) {
        Itinerary temporaryItinerary = itineraryMapper.selectItineraryByitinerary(itineraryVo.getItineraryCustomizeId(),
                                                                                    customerId);

        SimpleDateFormat mapperFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        PointRecord pointRecord = new PointRecord();
        if (temporaryItinerary != null &&
                (temporaryItinerary.getOrdersState() == null || temporaryItinerary.getOrdersState().equals("false")) &&
                temporaryItinerary.getItineraryAppraise() == null &&
                temporaryItinerary.getItineraryAppraiseContent() == null){

            pointRecord.setExpiredTime(new Date());

            List<PointRecord> pointRecordList = pointRecordMapper.selectPointRecordIntegral(customerId);
            Long count = 0l;
            for (PointRecord record : pointRecordList) {
                String departureDate = mapperFormat.format(new Date());
                String destinationDate = mapperFormat.format(record.getExpiredTime());

                long timeStart = 0l;
                long timeEnd = 0l;
                try {
                    timeStart = mapperFormat.parse(departureDate).getTime();
                    timeEnd = mapperFormat.parse(destinationDate).getTime();
                }catch (Exception e){
                    return 0;
                }

                long dayCount = timeEnd-timeStart;

                if (dayCount > 0){
                    count = count + record.getPntValue();
                }
            }

            PointRecord temporarypointRecord = new PointRecord();
            temporarypointRecord.setAvailableValue(count);
            temporarypointRecord.setCustomerId(customerId);

            pointRecordMapper.updatePointRecordByCustomerId(temporarypointRecord);

            pointRecord.setAvailableValue(count);
            pointRecord.setEmployeeId(1l);
            pointRecord.setCustomerId(customerId);
            pointRecord.setOrderType("customer");
            pointRecord.setPntValue(10l);
            pointRecord.setPntReasonDesc("行程评价");
            pointRecord.setOrderId(itineraryVo.getItineraryCustomizeId());
            pointRecord.setOperationTime(new Date());
            pointRecord.setPntDirection(1l);
            pointRecordMapper.insertPointRecord(pointRecord);


            itineraryVo.setOrdersState("true");
            return itineraryMapper.updateItineraryByItinerary(itineraryVo.getItineraryCustomizeId(),
                                                                itineraryVo.getItineraryAppraise(),
                                                                itineraryVo.getItineraryAppraiseContent(),
                                                                itineraryVo.getDropOff(),
                                                                itineraryVo.getVipRoom(),
                                                                itineraryVo.getFlight(),
                                                                itineraryVo.getPickUp(),
                                                                itineraryVo.getAnonymous(),
                                                                itineraryVo.getOrdersState(),
                                                                customerId);
        }
        else {
            throw new LoginException("该行程还未达到评价标准！");
        }
    }

    /**
     * 查看评价
     * */
    @Override
    public ItineraryVo selectItineraryByitinerary(Long itineraryCustomizeId, Long customerId) {
        Itinerary byitinerary = itineraryMapper.selectItineraryByitinerary(itineraryCustomizeId, customerId);
        ItineraryVo itineraryVo = new ItineraryVo();
        itineraryVo.setItineraryCustomizeId(itineraryCustomizeId);
        itineraryVo.setDeparturePoint(byitinerary.getDeparturePoint());
        itineraryVo.setDestination(byitinerary.getDestination());
        itineraryVo.setItineraryAppraise(byitinerary.getItineraryAppraise());
        itineraryVo.setItineraryAppraiseContent(byitinerary.getItineraryAppraiseContent());
        itineraryVo.setDropOff(byitinerary.getDropOff());
        itineraryVo.setVipRoom(byitinerary.getVipRoom());
        itineraryVo.setFlight(byitinerary.getFlight());
        itineraryVo.setPickUp(byitinerary.getPickUp());
        itineraryVo.setAnonymous(byitinerary.getAnonymous());
        return itineraryVo;
    }

    /**
     * 删除评价
     * */
    @Override
    public int updateItineraryByitinerary(Long itinerary) {
        return itineraryMapper.updateItineraryByitinerary(itinerary);
    }

    //定制行程-单程
    @Override
    public Map<String, Object> queryItineraryByCustomerId(String token) {
        Customer customer = iLoginService.getLoginCustomerByToken(token);
        Long customerId = customer.getCustomerId();
        Map<String, Object> map = new HashMap<>();

//        Map<String, Object> conveyorMap = new HashMap<>();
//        conveyorMap.put("departurePoint", "弘善家园东门");
//        conveyorMap.put("destination", "北京大兴国际机场");
//        conveyorMap.put("departureTime", "2021.11.25 09:23:45");
//        conveyorMap.put("useTime", "相距10公里·用时1小时6分");
//        conveyorMap.put("imgUrl", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic21.nipic.com%2F20120519%2F5908396_163026495324_2.jpg&refer=http%3A%2F%2Fpic21.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640234764&t=f1280ecf7c49d3b656e89657b70bbf9f");
//        conveyorMap.put("price", "136");
//        conveyorMap.put("memberPrice", "100");
//        conveyorMap.put("model", "舒适型（最多乘坐5人）");
//        conveyorMap.put("source", "阳光用车");
//        conveyorMap.put("type", "conveyor");
//        map.put("conveyor", conveyorMap);

        R<OrderViphallApi> orderViphallApiR = remoteService.queryItineraryHall(customerId);
        if (orderViphallApiR.getCode() == 200) {
            Map<String, Object> hall = remoteService.selectItineraryHall(orderViphallApiR.getData().getOrderviphallId());
            map.put("viphall", hall);
        }

        R<OrderVipchannelApi> orderVipchannelApiR = remoteService.queryItineraryChannel(customerId);
        if (orderVipchannelApiR.getCode() == 200) {
            Map<String, Object> channel = remoteService.selectItineraryChannel(orderVipchannelApiR.getData().getOrdervipchannelId());
            map.put("vipchannel", channel);
        }


        Map<String, Object> infoTickets = remoteFlightService.queryInfoTickets(customerId);
        map.put("flightTicket", infoTickets);

//        Map<String, Object> meetAircraftMap = new HashMap<>();
//        meetAircraftMap.put("departurePoint", "深圳宝安机场");
//        meetAircraftMap.put("destination", "东莞丽枫酒店");
//        meetAircraftMap.put("departureTime", "2021.11.25 09:23:45");
//        meetAircraftMap.put("imgUrl", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic21.nipic.com%2F20120519%2F5908396_163026495324_2.jpg&refer=http%3A%2F%2Fpic21.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640234764&t=f1280ecf7c49d3b656e89657b70bbf9f");
//        meetAircraftMap.put("price", "136");
//        meetAircraftMap.put("memberPrice", "100");
//        meetAircraftMap.put("model", "舒适型（最多乘坐5人）");
//        meetAircraftMap.put("source", "阳光用车");
//        meetAircraftMap.put("explain", "9月11日前 可免费取消");
//        meetAircraftMap.put("type", "meetAircraft");
//        map.put("meetAircraft", meetAircraftMap);
        return map;
    }

    /**
     * 行程-历史行程
     * @param token
     * @param customerId
     * @return
     */
    @Override
    public Map<String, Object> queryHistoryIyinerary(String token, Long customerId) {
        List<Itinerary> itinerarys = itineraryMapper.queryHistoryIyinerary(customerId);
        Map<String, Object> itinerarysMap = new HashMap<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date createTime = iLoginService.getLoginCustomerByToken(token).getCreateTime();
        if (createTime != null) {
            String format = dateFormat.format(createTime);
            try {
                Date date = new Date();
                Date create = dateFormat.parse(format);
                long time = date.getTime();
                long createDateTime = create.getTime();
                long joinDays = (time - createDateTime) / 60 / 60 / 24 / 1000;
                itinerarysMap.put("joinDays", joinDays);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        for (Itinerary itinerary : itinerarys) {
            Map<String, Object> map = new HashMap<>();
            map.put("itinerary", itinerary.getItineraryCustomizeId());
            map.put("departurePoint", itinerary.getDeparturePoint());
            map.put("destination", itinerary.getDestination());

            String departureTime = dateFormat.format(itinerary.getDepartureTime());
            map.put("departureTime", departureTime);
            String destinationTime = dateFormat.format(itinerary.getDestinationTime());
            map.put("destinationTime", destinationTime);
            List attachPathList = new ArrayList();
            for (ViphallAttachmentApi viphallAttachmentApi : itinerary.getViphallAttachmentApiList()) {
                String attachPath = viphallAttachmentApi.getAttachPath();
                attachPathList.add(attachPath);
            }
            map.put("viphallAttachment", attachPathList);
            mapList.add(map);
        }
        itinerarysMap.put("serviceNumber", itinerarys.size());
        itinerarysMap.put("totalMileage", "35167km");
        itinerarysMap.put("itinerary", mapList);
        return itinerarysMap;
    }

    /**
     * 查看行程
     * @param customerId
     * @param itinerary
     * @return
     */
    @Override
    public Map<String, Object> queryItineraryByCustomerIds(Long customerId, Long itinerary) {
        Itinerary itinerarys = itineraryMapper.queryItineraryByCustomerIds(customerId, itinerary);
        Map<String, Object> map = new HashMap<>();
        map.put("departurePoint", itinerarys.getDeparturePoint());
        map.put("destination", itinerarys.getDestination());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date departureTime = itinerarys.getDepartureTime();
        map.put("departureTime", dateFormat.format(departureTime));
        Date destinationTime = itinerarys.getDestinationTime();
        map.put("destinationTime", dateFormat.format(destinationTime));
        map.put("departureLatitudeLongitude", itinerarys.getDepartureLatitudeLongitude());
        map.put("destinationLatitudeLongitude", itinerarys.getDestinationLatitudeLongitude());

        Map<String, Object> conveyorMap = new HashMap<>();
        conveyorMap.put("departurePoint", "弘善家园东门");
        conveyorMap.put("destination", "北京大兴国际机场");
        conveyorMap.put("departureTime", "2021.11.25 09:23:45");
        conveyorMap.put("useTime", "相距10公里·用时1小时6分");
        conveyorMap.put("imgUrl", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic21.nipic.com%2F20120519%2F5908396_163026495324_2.jpg&refer=http%3A%2F%2Fpic21.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640234764&t=f1280ecf7c49d3b656e89657b70bbf9f");
        conveyorMap.put("model", "舒适型（最多乘坐5人）");
        conveyorMap.put("source", "阳光用车");
        conveyorMap.put("type", "conveyor");
        map.put("conveyor", conveyorMap);

        for (ItineraryMiddle itineraryMiddle : itinerarys.getItineraryMiddles()) {
            Long businessLineId = itineraryMiddle.getBusinessLineId();
            if ("viphall".equals(itineraryMiddle.getBusinessType())) {
                Map<String, Object> viphallTrip = remoteService.queryViphallTrip(businessLineId);
                map.put("viphall", viphallTrip);
                map.put("viphallDistance", itineraryMiddle.getStraightLineDistance());
                map.put("viphallServePlace", itineraryMiddle.getServePlace());
            } else if ("vipchannel".equals(itineraryMiddle.getBusinessType())) {
                Map<String, Object> vipchannelTrip = remoteService.queryVipchannelTrip(businessLineId);
                map.put("vipchannel", vipchannelTrip);
                map.put("vipchannelDistance", itineraryMiddle.getStraightLineDistance());
                map.put("vipchannelServePlace", itineraryMiddle.getServePlace());
            } else if ("flight".equals(itineraryMiddle.getBusinessType())) {
                Map<String, Object> flightOrderTrip = remoteFlightService.queryFlightOrderTrip(businessLineId);
                map.put("flight", flightOrderTrip);
                map.put("flightDistance", itineraryMiddle.getStraightLineDistance());
                map.put("flightServePlace", itineraryMiddle.getServePlace());
            }
        }

        Map<String, Object> meetAircraftMap = new HashMap<>();
        meetAircraftMap.put("departurePoint", "深圳宝安机场");
        meetAircraftMap.put("destination", "东莞丽枫酒店");
        meetAircraftMap.put("departureTime", "2021.11.25 09:23:45");
        meetAircraftMap.put("imgUrl", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic21.nipic.com%2F20120519%2F5908396_163026495324_2.jpg&refer=http%3A%2F%2Fpic21.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640234764&t=f1280ecf7c49d3b656e89657b70bbf9f");
        meetAircraftMap.put("model", "舒适型（最多乘坐5人）");
        meetAircraftMap.put("source", "阳光用车");
        meetAircraftMap.put("explain", "9月11日前 可免费取消");
        meetAircraftMap.put("type", "meetAircraft");
        map.put("meetAircraft", meetAircraftMap);
        return map;
    }

    @Override
    public List<FlightResponseVoApi> queryFlightList(MoFlightSearchRequestApi request) {
        List<FlightResponseVoApi> responseVos = remoteFlightService.getFlightInfoListBySearchConditions(request);
        return responseVos;
    }

    @Override
    public FightStopResVoApi getFightInfoByAirCodeAndDate(FightStopReqVoApi vo) {
        FightStopResVoApi fightInfoByAirCodeAndDate = remoteFlightService.getFightInfoByAirCodeAndDate(vo);
        return fightInfoByAirCodeAndDate;
    }

    /**
     * 新建行程
     * */
    @Override
    public Long addItinerary(Itinerary itinerary) throws Exception {
        Long itineraryCustomizeId = System.currentTimeMillis() / 1000;
        itinerary.setItineraryCustomizeId(itineraryCustomizeId);
        if (itinerary.getDeparturePoint() != null && !itinerary.getDeparturePoint().equals("")){
            Map<String, Object> map = new HashMap<>();
            map.put("cityName", itinerary.getDeparturePoint());
            String departurePointLngAndLat = remoteHotelService.dicCityLngAnfLat(map);
            int count = departurePointLngAndLat.indexOf(",");
            if (count > 0){
                itinerary.setDepartureLatitudeLongitude(departurePointLngAndLat);
            }
        }
        else {
            throw new Exception("出发城市不能为空");
        }

        if (itinerary.getDestination() != null && !itinerary.getDestination().equals("")){
            Map<String, Object> map = new HashMap<>();
            map.put("cityName", itinerary.getDestination());
            String destinationLngAndLat = remoteHotelService.dicCityLngAnfLat(map);
            int count = destinationLngAndLat.indexOf(",");
            if (count > 0){
                itinerary.setDestinationLatitudeLongitude(destinationLngAndLat);
            }
        }
        else {
            throw new Exception("目的地不能为空");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        itinerary.setCreateTime(format.parse(format.format(date)));

        List<CustomerCard> customerCardList = customerCardMapper.CustomerCardList(itinerary.getCustomerId());
        int count = 0;
        if (customerCardList != null && customerCardList.size() > 0){
            if (customerCardList.size() == 1){
                itinerary.setCardNumber(customerCardList.get(0).getCardCode());
            }
            else {
                for (CustomerCard customerCard : customerCardList) {
                    Card card = cardMapper.cardLevel(customerCard.getCardId());
                    if (card.getCardLevel() == 4l){
                        count = count + 1;
                    }
                    customerCard.setCardLevel(card.getCardLevel());
                }
                if (count < 2){
                    customerCardList.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
                    itinerary.setCardNumber(customerCardList.get(0).getCardCode());
                }
                else {
                    Date timeOne = null;
                    String cardNumOne = null;
                    Date timeTwo = null;
                    String cardNumTwo = null;
                    for (CustomerCard customerCard : customerCardList) {
                        if (customerCard.getCardLevel() == 4 && timeOne == null){
                            timeOne = customerCard.getInvalidDate();
                        }
                    }
                }
            }
        }

        int i = itineraryMapper.addItinerary(itinerary);
        if (i > 0){
            return itineraryCustomizeId;
        }
        else {
            throw new Exception("新建失败");
        }
    }
}
